<?php

namespace App\EventSubscriber\Wuliu;

use App\Base\BaseController;
use App\Event\PayEvent;
use App\Event\UserEvent;
use App\Repository\ConfigRepository;
use App\Repository\Wuliu\WuliuUserLevelRepository;
use App\Repository\Wuliu\WuliuUserRepository;
use App\Service\MoneyService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;

class PaySubscriber extends BaseController implements EventSubscriberInterface
{
    const EventFlag = "wuliu";
    public $levelRepository;
    public $wuliuUserRepository;
    public $configRepository;
    public $moneyService;

    public function __construct(
        ConfigRepository $configRepository
        ,WuliuUserLevelRepository $levelRepository
        ,WuliuUserRepository $wuliuUserRepository
        ,MoneyService $moneyService
    )
    {
        parent::__construct();
        $this->moneyService = $moneyService;
        $this->levelRepository = $levelRepository;
        $this->configRepository = $configRepository;
        $this->wuliuUserRepository = $wuliuUserRepository;
    }

    public static function getSubscribedEvents()
    {
        return [
            PayEvent::PAY_CHARGE => 'onPayCharge',
            PayEvent::PAY_ORDER => 'onPayOrder'
        ];
    }

    public function onPayCharge(PayEvent $event)
    {
        $payOrder = $event->getPayOrder();
        //先检查是否跟本项目有关，有关则处理
        if (in_array(self::EventFlag, $payOrder->getEventFlag())) {
            //处理相关请求
            if ($payOrder->getPayAt()) {
                return false;//已经处理过了
            }
            $request = Request::createFromGlobals();
            $data = [
                "get" => $_GET
                , "post" => $_POST
                , "input" => file_get_contents('php://input')
                , "req_request" => $request->request->all()
                , "req_query" => $request->query->all()
                , "request" => $request
                , "error" => ""
            ];
            $this->myEm()->beginTransaction();
            try {
                $payOrder->setPayAt(new \DateTime())->setData($data);
                //修改订单支付信息
                $user = $payOrder->getUser();
                $wUser = $this->wuliuUserRepository->findOneBy(array("user" => $user));
                if (!$wUser) {
                    $data["error"] = "未找到用户";
                    $payOrder->setData($data);
                } else {
                    //修改用户等级和会员日期
                    $wUserLevelCur = $wUser->getLevel();
                    $wLevels = $this->levelRepository->findAll();
                    foreach ($wLevels as $level) {
                        if ($level->getPrice() == $payOrder->getMoney()) {
                            //是否需要改变用户等级
                            if ($wUserLevelCur->getLevel() < $level->getLevel()) {
                                $wUser->setLevel($level);
                            }
                            //修改用户的会员期限
                            if ($wUser->getExpireAt()->getTimestamp() < time()) {
                                $time = time() + $level->getDays() * 24 * 3600;
                            }else{
                                $time = $wUser->getExpireAt()->getTimestamp() + $level->getDays() * 24 * 3600;
                            }
                            $wUser->setExpireAt(
                                new \DateTime(date(YYMMDDHHIISS, $time))
                            );
                            $this->myEm()->persist($wUser);

                        }
                    }
                    //计算返佣
                    $money = $this->configRepository->getByK("invite");

                    if ($money && $user->getParent()) {
                        $this->moneyService->mod($user->getParent(),$money,2,111,"推荐人升级返佣",[]);
                    }

                }
                $this->myEm()->persist($payOrder);
                $this->myEm()->flush();
            } catch (\Exception $exception) {
                $this->myEm()->rollback();
                throw $exception;
            }
            $this->myEm()->commit();
        }
    }

    public function onPayOrder(UserEvent $event)
    {
        $user = $event->getUser();
    }

}
